package core.domain.messages;

import java.io.Serializable;
import java.net.ServerSocket;

import javax.xml.bind.annotation.XmlRootElement;

import core.domain.DataFile;
import core.domain.PeerDesciptor;

@XmlRootElement
public   class AbstractMessage implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 3782887861278001854L;


	private AbstractMessage() {
	}
	
	private MessageType messageType;

	private PeerDesciptor peer;
	
	protected AbstractMessage(MessageType messageType) {
		this.messageType = messageType;
	}
	
	public MessageType getMessageType() {
		return messageType;
	}
	
	public void setMessageType(MessageType messageType) {
		this.messageType = messageType;
	}
	
	public PeerDesciptor getPeer() {
		return peer;
	}
	
	public void setPeer(PeerDesciptor peer){
		this.peer = peer;
	}
	public void setPeer(ServerSocket serverSocket) {
		this.peer = new PeerDesciptor(serverSocket.getInetAddress().getAddress(), serverSocket.getLocalPort());;
	}
	

	public static enum MessageType {
		NEWFILE,STATUS, STOPSERVER, REG, GETFILES, GETPEERSFORTORRENT, PING, GETPART, DISCONNECTION, AVAILABILITY, DATAFILE;
		public static Class<? extends AbstractMessage>  matchType(String xml){
			if(xml.contains("<messageType>NEWFILE</messageType>")){
				return NewFileMessage.class;
			} else if( xml.contains("<messageType>STATUS</messageType>")){
				return StatusMessage.class;
			} else if( xml.contains("<messageType>STOPSERVER</messageType>")){
				return StopServerMessage.class;
			} else if( xml.contains("<messageType>REG</messageType>")){
				return RegisterMessage.class;
			} else if( xml.contains("<messageType>GETFILES</messageType>")){
				return GetFilesMessage.class;
			} else if( xml.contains("<messageType>GETPEERSFORTORRENT</messageType>")){
				return GetPeersForTorrentMessage.class;
			} else if( xml.contains("<messageType>PING</messageType>")){
				return PingPongMessage.class;
			} else if( xml.contains("<messageType>GETPART</messageType>")){
				return GetPartMessage.class;
			} else if( xml.contains("<messageType>DISCONNECTION</messageType>")){
				return DisconnectionMessage.class;
			} else if( xml.contains("<messageType>AVAILABILITY</messageType>")){
				return AvailabilityMessage.class;
			} else if( xml.contains("<messageType>DATAFILE</messageType>")){
				return DataFile.class;
			} else {
				return DisconnectionMessage.class;
			}
		}
	}


	@Override
	public String toString() {
		return "AbstractMessage [messageType=" + messageType + ", peer=" + peer + "]";
	}
	
	
	
}
